/**
 * 
 */
package com.gr.staffpm.google.utils;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import com.gr.staffpm.pages.schedule.Schedule;
import com.gr.staffpm.pages.schedule.model.Calendar;
import com.gr.staffpm.pages.schedule.model.Event;
import com.gr.staffpm.security.service.UserService;


/**
 * @author Graham Rhodes 31 Mar 2011 12:51:56
 */
public class GCalUtils {

    private static final Logger log = LoggerFactory.getLogger(GCalUtils.class);

    public static List<Event> getAndProcessGcalEvents(Schedule schedule, UserService userService, DateTime start, DateTime end) {
        List<Event> gcalEvents = new ArrayList<Event>();
        try {
            com.google.gdata.data.DateTime startTime = new com.google.gdata.data.DateTime(start.toDate());
            com.google.gdata.data.DateTime endTime = new com.google.gdata.data.DateTime(end.toDate());
            URL eventFeedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
            CalendarQuery query = new CalendarQuery(eventFeedUrl);
            query.setMinimumStartTime(startTime);
            query.setMaximumStartTime(endTime);
            //query.setStringCustomParameter("fields", "entry(title,gd:when)");
            query.setStringCustomParameter("singleevents", "true");
            query.setStringCustomParameter("showdeleted", "false");

            CalendarService service = new CalendarService("GrahamRhodes-StaffPM-0.1-SNAPSHOT");
            service.setUserToken(userService.getCurrentUser().getGcalAuth());
            // Send the request and receive the response:
            CalendarEventFeed resultFeed = service.query(query, CalendarEventFeed.class);

            //log.info("Events from " + startTime.toString() + " to " + endTime.toString() + ":\n");
            Calendar cal = new Calendar(2, "Google Calendar");
            schedule.addCalendar(cal);
            for (int i = 0; i < resultFeed.getEntries().size(); i++) {
                CalendarEventEntry entry = resultFeed.getEntries().get(i);
                if (!entry.getTimes().isEmpty()) {
                    //log.info("\t" + entry.getTitle().getPlainText());
                    Event evt = new Event();
                    When when = entry.getTimes().get(0);
                    DateTime startDate = new DateTime(when.getStartTime().getValue());
                    DateTime endDate = new DateTime(when.getEndTime().getValue());
                    Period p = new Period(startDate, endDate, PeriodType.days());
                    //log.info("\tIs Single All Day: " + p.getDays());
                    boolean isAllDay = when.getStartTime().isDateOnly();
                    evt.setAllDay(isAllDay);
                    //log.info("\tStart: " + when.getStartTime().toString());
                    evt.setStart(startDate);
                    evt.setCalendar(cal);
                    //log.info("\tEnd: " + when.getEndTime().toString());
                    evt.setEnd(isAllDay ? startDate.plusDays(p.getDays() - 1) : new DateTime(when.getEndTime().getValue()));
                    evt.setTitle((!isAllDay) ? startDate.toString("KK:mm a ") + entry.getTitle().getPlainText() : entry.getTitle().getPlainText());
                    gcalEvents.add(evt);
                }
            }
        } catch (Exception e) {
            log.error("Exception getting calendars from google.", e);
        }
        return gcalEvents;
    }
}
